package com.cheyunkeji.er.activity.auction;

import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.aspsine.swipetoloadlayout.OnLoadMoreListener;
import com.aspsine.swipetoloadlayout.OnRefreshListener;
import com.cheyun.netsalev3.R;
import com.cheyunkeji.er.adapter.auction.ApplyRecordAdapter;
import com.cheyunkeji.er.base.BaseActivity;
import com.cheyunkeji.er.bean.auction.ApplyRecordBean;
import com.cheyunkeji.er.http.ApiClient;
import com.cheyunkeji.er.http.HttpConstants;
import com.cheyunkeji.er.http.RespCallback;
import com.cheyunkeji.er.view.SToast;
import com.cheyunkeji.er.view.SwipeLayout;
import com.cheyunkeji.er.view.TopBar;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class ApplyRecordActivity extends BaseActivity implements OnRefreshListener, OnLoadMoreListener, TextWatcher {


    //    每页数据量
    private static final int COUNTS_PER_PAGE = 10;
    //    当前列表状态 STATE_REFRESH : 下拉刷新 ，STATE_LOADMORE : 上拉加载更多
    private static int CURRENT_REFRESH_STATE = SwipeLayout.STATE_REFRESH;
    //     当前页数
    private static int CURRENT_LOAD_PAGE = 1;
    //    搜索关键字
    private static String KEY_WORDS = null;
    @BindView(R.id.iv_search)
    ImageButton ivSearch;
    @BindView(R.id.et_search_content)
    EditText etSearchContent;
    @BindView(R.id.tv_search_content)
    TextView tvSearchContent;
    @BindView(R.id.ll_empty_content_display)
    LinearLayout llEmptyContentDisplay;
    @BindView(R.id.swipe_target)
    ListView swipeTarget;
    @BindView(R.id.swipe_layout)
    SwipeLayout swipeLayout;
    @BindView(R.id.v_topbar)
    TopBar vTopbar;
    private ArrayList<ApplyRecordBean> dataList;
    private ApplyRecordAdapter adapter;
    private Handler uiRefreshHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {

            switch (msg.what) {

                case SwipeLayout.STATE_NORMAL:

                    if (CURRENT_REFRESH_STATE == SwipeLayout.STATE_REFRESH) {

                        onRefreshSuccessed((ArrayList<ApplyRecordBean>) msg.obj);
                    } else {

                        onLoadMoreSuccessed((ArrayList<ApplyRecordBean>) msg.obj);
                    }

                    break;

                case SwipeLayout.STATE_SEARCH_BY_KEYWORD:

                    if (CURRENT_REFRESH_STATE == SwipeLayout.STATE_REFRESH) {

                        onRefreshSuccessed((ArrayList<ApplyRecordBean>) msg.obj);
                    } else {

                        onLoadMoreSuccessed((ArrayList<ApplyRecordBean>) msg.obj);
                    }

                    break;

                default:
                    break;

            }

        }
    };

    /**
     * 上拉加载成功刷新
     *
     * @param newList
     */
    private void onLoadMoreSuccessed(ArrayList<ApplyRecordBean> newList) {

        if (newList != null) {

            if (newList.size() != 0) {

                swipeLayout.endLoadMore();
                dataList.addAll(newList);
                adapter.notifyDataSetChanged();
                CURRENT_LOAD_PAGE ++ ;

            } else {

                swipeLayout.endLoadMore();
                swipeLayout.setLoadMoreEnabled(false);

            }
        }
    }


    private void onRefreshSuccessed(ArrayList<ApplyRecordBean> newList) {

        if (newList != null && newList.size() != 0) {
            hideEmptyView();
            dataList.clear();
            dataList.addAll(newList);
            adapter.notifyDataSetChanged();
            CURRENT_LOAD_PAGE ++ ;

        } else if (newList.size() == 0) {
            showContentEmptyView();
            dataList.clear();
            adapter.notifyDataSetChanged();
        }
        swipeLayout.endRefresh();

    }


    @Override
    protected void init() {
        KEY_WORDS = "";
        setContentView(R.layout.er_activity_apply_record);
        ButterKnife.bind(this);

    }

    @Override
    protected void initView() {
        vTopbar.setLeftBack();
        vTopbar.setTitle("申请记录");
        swipeLayout.setOnRefreshListener(this);
        swipeLayout.setOnLoadMoreListener(this);
        ivSearch.setOnClickListener(this);
        etSearchContent.addTextChangedListener(this);
    }

    @Override
    protected void initData() {
        dataList = new ArrayList<>();
        adapter = new ApplyRecordAdapter(dataList, this);
        swipeTarget.setAdapter(adapter);
        onRefresh();
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {

            case R.id.iv_search:

                KEY_WORDS = etSearchContent.getText().toString().trim();
//                swipeLayout.setRefreshing(true);
                onRefresh();

                break;

            default:
                break;

        }
    }

    @Override
    public void onRefresh() {
        CURRENT_REFRESH_STATE = SwipeLayout.STATE_REFRESH;
        CURRENT_LOAD_PAGE = 1;
        loadCarArchiveList(CURRENT_LOAD_PAGE, COUNTS_PER_PAGE, KEY_WORDS);
        swipeLayout.setLoadMoreEnabled(true);
    }

    @Override
    public void onLoadMore() {
        CURRENT_REFRESH_STATE = SwipeLayout.STATE_LOADMORE;
        loadCarArchiveList(CURRENT_LOAD_PAGE, COUNTS_PER_PAGE, KEY_WORDS);
    }

    private void hideEmptyView() {

        //swipeLayout.setVisibility(View.VISIBLE);
        llEmptyContentDisplay.setVisibility(View.INVISIBLE);

    }


    private void showContentEmptyView() {

        //swipeLayout.setVisibility(View.INVISIBLE);

        if(!TextUtils.isEmpty(KEY_WORDS)) {
            llEmptyContentDisplay.setVisibility(View.VISIBLE);
            tvSearchContent.setText(KEY_WORDS);
        }else{
            llEmptyContentDisplay.setVisibility(View.INVISIBLE);
        }
    }

    private void loadCarArchiveList(int currentLoadPage, int countsPerPage, final String keyWords) {

        HashMap<String, String> params = new HashMap<>();
//        params.put("authkey", UserInfoManager.getInstance(MyApplication.getInstance()).getAuthKey());
//        params.put(ChannelInfoUtil.getCurrentChannelInfo().getCkey1().getYkey(), ChannelInfoUtil.getCurrentChannelInfo().getCkey1().getY7e_e73a691f02a46500201c3998e6a2989d());
        params.put("page", String.valueOf(currentLoadPage));
        params.put("rows", String.valueOf(countsPerPage));
        if (!TextUtils.isEmpty(keyWords))
            params.put("keywords", keyWords);

        ApiClient.postForm(HttpConstants.APPLY_RECORD_LIST, params, new RespCallback<List<ApplyRecordBean>>() {

                    @Override
                    protected void onRequestFailed(String msg) {

                        SToast.show(msg);

                        if (CURRENT_REFRESH_STATE == SwipeLayout.STATE_REFRESH) {
                            swipeLayout.endRefresh();
                        } else if (CURRENT_REFRESH_STATE == SwipeLayout.STATE_LOADMORE) {
                            swipeLayout.endLoadMore();
                        }
                    }

                    @Override
                    protected void onSuccess(List<ApplyRecordBean> data) {

                        Message msg = uiRefreshHandler.obtainMessage();
                        msg.what = TextUtils.isEmpty(keyWords) ? SwipeLayout.STATE_NORMAL : SwipeLayout.STATE_SEARCH_BY_KEYWORD;
                        msg.obj = data;
                        uiRefreshHandler.sendMessage(msg);

                    }

                    @Override
                    public void onError(Exception e) {
                        super.onError(e);

                        if (CURRENT_REFRESH_STATE == SwipeLayout.STATE_REFRESH) {
                            swipeLayout.endRefresh();
                        } else if (CURRENT_REFRESH_STATE == SwipeLayout.STATE_LOADMORE) {
                            swipeLayout.endLoadMore();
                        }
                    }
                }
        );

    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        if (TextUtils.isEmpty(s.toString())) {
            KEY_WORDS = null;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        uiRefreshHandler.removeCallbacksAndMessages(null);
    }
}
